<script setup lang="ts">
import { Form } from '@/components/Form'
import { ElInput, ElButton, ElRow, ElCol } from "element-plus"
import { useForm } from '@/hooks/web/useForm'
import { PropType, reactive, watch, ref, unref, nextTick } from 'vue'
import { FormSchema } from '@/types/form'
import { WorkData } from "@/api/manage/work/types";
import { Dialog } from '@/components/Dialog'
import Select from "@/views/manage/data/select.vue";

const props = defineProps({
  currentRow: {
    type: Object as PropType<Nullable<WorkData>>,
    default: () => null
  },
  formSchema: {
    type: Array as PropType<FormSchema[]>,
    default: () => []
  }
})

const rules = reactive({
})

const { register, methods, elFormRef } = useForm({
  schema: props.formSchema
})

watch(
  () => props.currentRow,
  (currentRow) => {
    if (!currentRow) return
    const { setValues } = methods
    setValues(currentRow)
  },
  {
    deep: true,
    immediate: true
  }
)

defineExpose({
  elFormRef,
  getFormData: methods.getFormData
})


const dialogRef = ref<ComponentRef<typeof Dialog>>();
const selectRef = ref<ComponentRef<typeof Select>>();

const dialogVisible = ref(false)
const loading = ref(false)

const showSelect = async () => {
  dialogVisible.value = true;
  await nextTick();
  const dialogObj = unref(dialogRef);
  dialogObj?.toggleFull();
}

const selected = async () => {
  const selectObj = unref(selectRef);
  const selectedRows = await selectObj?.getSelected();
  const { setValues } = methods
  let dataIds: number[] = [];
  if (selectedRows && selectedRows?.length > 0) {
    dataIds = selectedRows.map(data => data.service_id);
  }
  setValues({
    data_service_list: dataIds,
    txt_data_service_list: dataIds.join(",")
  })
  dialogVisible.value = false;
}

const cancel = () => {
  dialogVisible.value = false;
}
</script>

<template>
  <div>

    <Form :rules="rules" @register="register">
      <template #total_space-append>GB</template>
      <template #txt_data_service_list="{ txt_data_service_list }">
        <el-row :gutter="6">
          <el-col :span="16"><el-input :model-value="txt_data_service_list" placeholder="请选择" /></el-col>
          <el-col :span="6"><el-button type="primary" @click="showSelect">选择秘文端</el-button></el-col>
        </el-row>
      </template>
    </Form>
  </div>
  <Dialog v-if="dialogVisible" ref="dialogRef" v-model="dialogVisible" title="选择秘文端" :width="800" :max-height="550">
    <Select ref="selectRef" />

    <template #footer>
      <ElButton @click="cancel">取消</ElButton>
      <ElButton type="primary" :loading="loading" @click="selected">
        确定
      </ElButton>
    </template>
  </Dialog>
</template>
